<template>
  <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :on-change="handleAvatarChange"
    :auto-upload="false"
    accept="image/*"
  >
    <img v-if="avatar" :src="avatar" class="avatar" :style="{ width, height }">
    <v-icon v-else class="avatar-uploader-icon" :style="{ width, height }">add</v-icon>
  </el-upload>
</template>

<script>
export default {
  name: 'AvatarUpload',
  props: {
    avatar: {
      type: String,
      required: true
    },
    edge: {
      type: Number,
      default: 178
    }
  },
  computed: {
    width() {
      return this.edge + 'px'
    },
    height() {
      return this.edge + 'px'
    }
  },
  methods: {
    handleAvatarChange(file) {
      const isImage = file.raw.type.indexOf('image') >= 0
      const isFit = file.size / 1024 / 1024 < 1
      if (!isImage) return this.$notify.error('只能上传图片类型')
      if (!isFit) return this.$notify.error('图片大小应不超过1M')
      // to Base64
      const render = new FileReader()
      render.onload = () => {
        this.avatar = render.result
        this.$emit('update:avatar', render.result)
      }
      render.readAsDataURL(file.raw)
    }
  }
}
</script>

<style lang="scss">
  .avatar-uploader .el-upload{
    border: 1px dashed #aaa;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    display: block;
  }
</style>

<style scoped>

</style>
